package com.ming.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Auther: tangC
 * @Date: 2020/7/7 14:11
 * @Description:
 */

@Slf4j
public class TimeFilterLimpl implements GatewayFilter,Ordered {


    private static final String COUNT_start_TIME = "countsStartTime";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(COUNT_start_TIME,System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(()->{
            Long startTime = exchange.getAttribute(COUNT_start_TIME);
            Long timeUsed = (System.currentTimeMillis() -startTime);
            if (startTime != null){
                log.info(exchange.getRequest().getURI().toASCIIString()+":"+timeUsed+"ms");
            }
        }));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
